const fs = require('fs');

const userService = require('../service/user.service');
const removeAvatar = require('../utils/removeAvatar-handle');
const {AVATAR_PATH} = require('../constants/file-path');

class UserController {
  async createUser(ctx, next) {
    const {name, password} = ctx.request.body;

    const result = await userService.addUser(name, password);
    
    ctx.body = result;
  }

  async getUserAvatar(ctx, next) {
    const {userId} = ctx.params;
    
    const result = await userService.getAvatarById(userId);
    
    ctx.response.set('content-type', result.mimetype);
    ctx.body = fs.createReadStream(`${AVATAR_PATH}/${result.filename}`);
  }

  async removeUser(ctx, next) {
    const {id} = ctx.request.body;
    
    const result = await userService.removeUserById(id);
    removeAvatar(result.filename);

    ctx.body = '用户注销成功！';
  }
}

module.exports = new UserController();